<script setup lang="ts">
	import * as monaco from 'monaco-editor'
	import { onMounted, onUnmounted, ref, watch } from 'vue'

	const props = defineProps<{
		originValue: string
		modifiedValue: string
		language?: string
		height?: string
	}>()
	const emits = defineEmits(['updateLines'])

	const containerRef = ref<HTMLElement>()

	const language = props.language || 'text/plain'

	const originalModel = monaco.editor.createModel(props.originValue, language)
	const modifiedModel = monaco.editor.createModel(props.modifiedValue, language)

	let diffEditor: monaco.editor.IStandaloneDiffEditor

	const getGreenLineCount = () => {
		const lineChanges = diffEditor.getLineChanges()
		console.log(lineChanges)
		let greenLineCount = 0
		greenLineCount += lineChanges!.length
		lineChanges?.forEach((change) => {
			// 判断是否有修改行
			if (change.modifiedEndLineNumber > change.modifiedStartLineNumber) {
				// 计算右侧修改的行数（绿色行）
				greenLineCount += change.modifiedEndLineNumber - change.modifiedStartLineNumber
			}
		})

		return greenLineCount
	}

	const initEditor = () => {
		try {
			diffEditor = monaco.editor.createDiffEditor(containerRef.value!, {
				readOnly: true,
				originalEditable: false,
				automaticLayout: true,
				renderOverviewRuler: false,
				ignoreTrimWhitespace: false,
				// diffWordWrap: 'on',
			})
			diffEditor.setModel({
				original: originalModel,
				modified: modifiedModel,
			})
			diffEditor.onDidUpdateDiff(() => {
				const greenLineCount = getGreenLineCount()
				emits('updateLines', greenLineCount)
			})
		} catch (error) {
			console.log('🚀 ~ initEditor ~ error:', error)
		}
	}

	onMounted(() => {
		initEditor()
	})

	onUnmounted(() => {
		diffEditor?.dispose()
	})

	watch(
		() => props.originValue,
		() => originalModel.setValue(props.originValue),
	)
	watch(
		() => props.modifiedValue,
		() => modifiedModel.setValue(props.modifiedValue),
	)
</script>

<template>
	<div :style="{ height: props.height || '350px' }" ref="containerRef" />
</template>

<style scoped lang="scss">
	/* 增加行号区域的宽度 */
	.monaco-editor .margin {
		width: 65px !important; /* 默认是50px，根据字体大小调整 */
	}

	/* 确保行号不换行 */
	// .monaco-editor .line-numbers {
	// 	white-space: nowrap;
	// 	text-align: right;
	// 	padding-right: 10px;
	// 	font-feature-settings: 'tnum'; /* 使用等宽数字 */
	// }
	:deep(.monaco-editor .line-numbers) {
		font-family: 'Consolas', 'Courier New', monospace;
		font-feature-settings: 'tnum';
		text-align: right;
		padding-right: 10px;
		white-space: nowrap;
	}
</style>
